import { ApiMsgEnum, IApiLoginReq, IPlayer, Singleton } from "../Common";
import { Connection } from "../Core/Connection";
import { Player } from "./Player";
import { RoomManager } from "./RoomManager";

export class PlayerManager extends Singleton {
    static get Ins() {
        return super.GetInstance<PlayerManager>()
    }

    players: Set<Player> = new Set()
    idMapPlayers: Map<number, Player> = new Map()
    nextPlayerId: number = 1

    creatPlayer({ connection, nickName }: { connection: Connection } & IApiLoginReq) {

        const player = new Player({
            id: this.nextPlayerId++,
            connection,
            nickName
        })

        this.players.add(player)
        this.idMapPlayers.set(player.id, player)
        return player
    }

    removePlayer(id: number) {
        const player = this.idMapPlayers.get(id)
        if (player) {
            this.idMapPlayers.delete(player.id)
            this.players.delete(player)
            console.log(`玩家${player.nickName}被移除`)
        }
    }

    getPlayersView(players: Set<Player> = this.players): IPlayer[] {
        return [...players].map(v => this.getPlayerView(v))
    }

    getPlayerView({ id, nickName, rid, ready }: IPlayer) {
        return { id, nickName, rid, ready }
    }

    /** 检查昵称是否重复 */
    checkNickName(nickName: string) {
        for (const player of PlayerManager.Ins.players) {
            if (player.nickName == nickName) {
                return true
            }
        }
    }

    /** 玩家离线 */
    playerOffline(playerId: number) {
        const player = this.idMapPlayers.get(playerId)
        if (player) {
            // 玩家在房间中
            if (player.rid) {
                const room = RoomManager.Ins.idMapRoom.get(player.rid)
                if (room) {
                    // 是否保持断线重连状态
                    if (room.playerOffline(player)) {
                        console.log(`玩家${player.nickName}掉线了`)
                        return
                    }
                }
            }
            console.log(`玩家${player.nickName}断开了链接`)
            this.removePlayer(playerId)
        }
    }

    /** 断线重连,恢复数据 */
    playerOfflineLaunch(nickName: string, connection: Connection): false | IPlayer {
        const players = [...this.players]
        for (const player of players) {
            if (player.nickName == nickName) {
                if (player.isOnline) {
                    throw new Error('已登录')
                }
                const room = RoomManager.Ins.getRoomById(player.rid)
                // 重连成功，重新绑定监听、链接
                if (room && room.isGaming) {
                    connection.playerId = player.id
                    player.connection = connection
                    player.isOnline = true
                    player.connection.listening(ApiMsgEnum.MsgClientSync, room.getClientMsg, room)

                    return PlayerManager.Ins.getPlayerView(player)
                }
            }
        }

        return false
    }
}